// import Account from './account'
import Config from '@/config'
// import iView from 'iview'

var websocket = null
var listeners = []

export default {
  setup (onMessage) {
    let self = this
    websocket = new WebSocket(`ws://${Config.HOST}/`)
    websocket.onmessage = function (event) {
      let msg = JSON.parse(event.data)
      if (onMessage) {
        onMessage(msg)
      }
      self.onMessage(msg)
    }

    websocket.onopen = function (event) {
      console.log('websocket 连接打开')
    }
    websocket.onclose = function (event) {
      console.log('websocket 连接关闭')
    }
  },
  teardown () {
    if (websocket) {
      websocket.close()
    }
  },
  getWebSocket () {
    return websocket
  },
  onMessage (msg) {
    for (let listener of listeners) {
      listener(msg)
    }
  },
  addListener (listener) {
    listeners.push(listener)
  },
  removeListener (listener) {
    let index = listeners.indexOf(listener)
    if (index >= 0) {
      listeners.splice(index, 1)
    }
  }
}
